// https://zhaoqize.github.io/puppeteer-api-zh_CN/#/
import {app} from 'electron'

var protobuf = require("protobufjs");
//抖音直播
var liveListener = async (page, link, event) => {

    await page.setJavaScriptEnabled(true);
    //结果
    console.log('--------------------------------------------------------------------')
    console.log("进入打开抖音直播：" + link)
    await page.goto(link);

    //静音
    await page.waitForSelector('video')
    await page.evaluate(() => {
        for (let video of document.querySelectorAll('video')) {
            video.muted = true
        }
    })

    page.on('response', function (response) {
        if (response.url().startsWith("https://live.douyin.com/webcast/im/fetch/")) {
            response.buffer().then(function (bufferArray) {
                protobuf.load(app.getAppPath() + '/../src/core/proto/douyinMessage.proto', function (err, root) {
                    if (err) {
                        console.error(err)
                        return;
                    }
                    // 获得 message 类型
                    var DYDM = root.lookupType("DYDM");
                    var ChatMessage = root.lookupType("ChatMessage");

                    var DYDMMessageObj = DYDM.decode(new Uint8Array(bufferArray));

                    for (let msg of DYDMMessageObj['messages']) {
                        if (msg['method'].endsWith('ChatMessage')) {
                            var ChatMessageObj = ChatMessage.decode(msg['payload']);
                            // console.log(ChatMessageObj.user.nickname + "说：" + ChatMessageObj.content);
                            event.reply('douyinLiveChatMessage', ChatMessageObj)
                        }
                    }
                });
            });
        } else {
        }
    });
}

export default liveListener
